/**
 * package br.com.carser.ejb.
 */
package br.com.webdol.ejb;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Entity implementation class for Entity: Enterprise
 * @author Caio Carleto. 03/05/2011 16:44:54.
 */
public class BaseSessionBean implements Serializable {

	/**
	 * Serial version.
	 */
	private static final long serialVersionUID = 5482338851158823351L;
	
	/**
	 * Entity Manager.
	 */
	@PersistenceContext
	private EntityManager em;
		
	/**
	 * @return the em.
	 */
	public EntityManager getEm() {
		return em;
	}
	
	@SuppressWarnings("unchecked")
	public <T> List<T> getList(Class<T> classToCast, String query, Object... values){
		Query qr = createQuery(query, values);
		return qr.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public <T> T getSingleResult(Class<T> classToCast, String query, Object... values){
		Query qr = createQuery(query, values);
		return (T) qr.getSingleResult();
	}
	
	public <T> T getSingleByPK(Class<T> classToCast, Serializable pk){
		return em.find(classToCast, pk);
	}
	
	public int execute(String query, Object... values){
		Query qr = createQuery(query, values);
		return qr.executeUpdate();
	}

	private Query createQuery(String query, Object[] values) {
		Query qr = em.createQuery(query);
		if(values != null){
			for(int i = 0; i < values.length; i++){
				Object obj = values[i];
				int a = i + 1;
				qr.setParameter(a, obj);
			}
		}
		return qr;
	}

}
